package com.blockchain.securewallet.activities;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blockchain.securewallet.MainActivity;
import com.blockchain.securewallet.R;
import com.blockchain.securewallet.WalletApp;
import com.blockchain.securewallet.adapter.WordsAdapter;
import com.blockchain.securewallet.base.BaseActivity;
import com.blockchain.securewallet.dialog.CommonDialogFragment;
import com.blockchain.securewallet.dialog.DialogFragmentHelper;
import com.blockchain.securewallet.dialog.IDialogTipsListener;
import com.blockchain.securewallet.dialog.UniversalDialog;
import com.blockchain.securewallet.model.db.Account;
import com.blockchain.securewallet.model.db.CoinWallet;
import com.blockchain.securewallet.model.db.oper.AccountDaoOpe;
import com.blockchain.securewallet.tools.SpaceItemDecoration;
import com.blockchain.securewallet.tools.TipsWatcher;
import com.blockchain.securewallet.utils.Logger;
import com.blockchain.securewallet.utils.UIHelper;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class SeedVerifyActivity extends BaseActivity implements WordsAdapter.IWordChangeWatch, WordsAdapter.IWordClickListener, WordsAdapter.ISeedClickListener {

    public static final String KEY_WORDS_LIST = "words_list";

    @BindView(R.id.tv_title)
    TextView tvTitle;

    @BindView(R.id.rv_seed_edit)
    RecyclerView rvSeedEdit;

    @BindView(R.id.rv_seed_words)
    RecyclerView rvSeedWord;

    //幕布
    @BindView(R.id.fl_curtain)
    FrameLayout flCurtain;

    private WordsAdapter adapterEdit = null;
    private WordsAdapter adapterPreview = null;
    //传递过来的助记词
    private String strCode;
    //需要验证的助记词
    private List<String> editSeeds = new ArrayList<>(12);

    private String password = "";

    private ArrayList<String> listMnemonic;
    //打乱后预览框的种子集
    private List<String> mPreLists;

    private PowerManager.WakeLock m_wklk;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seed_verify);
        ButterKnife.bind(this);

        //关闭输入法
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        tvTitle.setText(R.string.verify_seed);

        Intent intent = getIntent();
        if (intent != null) {
            strCode = intent.getStringExtra(KEY_WORDS_LIST);
        }
        mPreLists = Arrays.asList(strCode.split("\\s+"));
        Collections.shuffle(mPreLists);

        adapterPreview = new WordsAdapter(this, mPreLists);
        adapterPreview.setWordListener(this);
        rvSeedWord.setLayoutManager(new GridLayoutManager(this, 3));
        rvSeedWord.addItemDecoration(new SpaceItemDecoration(UIHelper.dipToPx(1.5f)));
        rvSeedWord.setAdapter(adapterPreview);

        for (int i = 0; i < 12; i++) {
            editSeeds.add("");
        }

        adapterEdit = new WordsAdapter(this, editSeeds);
        adapterEdit.setType(1);
        adapterEdit.setWatcher(this);
        adapterEdit.setiSeedClickListener(this);

        rvSeedEdit.setLayoutManager(new GridLayoutManager(this, 3));
        rvSeedEdit.addItemDecoration(new SpaceItemDecoration(UIHelper.dipToPx(1.5f)));
        rvSeedEdit.setAdapter(adapterEdit);
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @OnClick(R.id.btn_back)
    void back() {
        finish();
    }

    @OnClick(R.id.btn_next)
    void next() {

        if (!verifySeeds()) {
            Toast.makeText(this, "种子密码校验失败", Toast.LENGTH_SHORT).show();
            return;
        }

        UniversalDialog dialog = UniversalDialog.showDialog(getSupportFragmentManager(), new IDialogTipsListener() {

            @Override
            public void onItemClick(View view, String... texts) {
                if (texts.length != 2) {
                    return;
                }

                final TextView tv_err = view.findViewById(R.id.tv_tips_pw_err);
                EditText edit_first_pw = view.findViewById(R.id.edit_first_password);
                EditText edit_second_pw = view.findViewById(R.id.edit_second_password);

                TipsWatcher watcher = new TipsWatcher(tv_err, true);
                edit_first_pw.addTextChangedListener(watcher);
                edit_second_pw.addTextChangedListener(watcher);

                if (TextUtils.isEmpty(texts[0]) || TextUtils.isEmpty(texts[1])) {
                    tv_err.setText("*密码不能为空");
                    tv_err.setVisibility(View.VISIBLE);

                } else if (texts[0].length() < 5 || texts[1].length() < 5) {
                    tv_err.setText("*密码长度不能小于5位");
                    tv_err.setVisibility(View.VISIBLE);

                } else if (!texts[0].equals(texts[1])) {
                    tv_err.setText("*两次密码输入不一致");
                    tv_err.setVisibility(View.VISIBLE);

                } else {
                    password = texts[0];
                    generateWalletAsync();
                }
                //Toast.makeText(SeedVerifyActivity.this,"ok-->"+text1.equals(text2),Toast.LENGTH_SHORT).show();
            }
        });

        //finish();
    }

    private void generateWalletAsync() {
        new AsyncTask<Void, Void, Void>() {
            CommonDialogFragment loadDialog;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                flCurtain.setVisibility(View.VISIBLE);
                loadDialog = DialogFragmentHelper.showProgress(getSupportFragmentManager(), getString(R.string.wallet_loading_create), false);
            }

            @Override
            protected Void doInBackground(Void... voids) {
//                WalletApp.getInstance().getDaoSession().getUnSpentDao().deleteAll();

                PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
                m_wklk = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "cn");
                m_wklk.acquire(); //设置保持唤醒


                List<CoinWallet> coinWallets = new ArrayList<>();
                coinWallets.addAll(CoinWallet.createAllWallet(strCode, password));
                Account account = new Account();
                account.setAccountId(WalletApp.uuid);
                account.setPayPassword(password);
                account.setTime(System.currentTimeMillis());
                account.setMemorizing_words(strCode);
                account.setCoinWalletList(coinWallets);
                AccountDaoOpe.insertData(SeedVerifyActivity.this, account);


//                WalletApp.getInstance().getDaoSession().insert(bitCoinWallet);
//                WalletApp.getInstance().getDaoSession().insert(etherWallet);
//                WalletApp.getInstance().saveWordsList(strCode);
//                WalletApp.getInstance().savePayPassword(password);
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                try {
                    if (loadDialog != null) {
                        loadDialog.dismiss();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("errors", "onPostExecute:create dialog dismiss err: " + e.getMessage(), e.fillInStackTrace());
                } finally {
                    MainActivity.startFromWalletCreate(SeedVerifyActivity.this);
                    m_wklk.release(); //解除保持唤醒
                    finish();

                }



            }
        }.execute();
    }

    private boolean verifySeeds() {
        List<String> words = Arrays.asList(strCode.split("\\s+"));
        for (int i = 0; i < words.size(); ++i) {
            if (!words.get(i).equals(editSeeds.get(i)))
                return false;
        }
        return true;
    }


    @Override
    public void dataChanged(final int pos, String text) {

    }


    @Override
    public void clickListener(int pos, String text) {
        //获取有焦点的EditText的位置
//        rvSeedEdit.
        /*for (int i = 0; i < rvSeedEdit.getChildCount(); i++) {
            if (rvSeedEdit.getChildAt(i).hasFocus()) {
                editSeeds.remove(i);
                editSeeds.add(i, text);
                adapterEdit.notifyItemChanged(i);
                
                Log.i("testtest", editSeeds.toString());
                return;
            }
        }*/
        Logger.ds("点击了预览界面的第" + pos + "个: " + text);

        for (int i = 0; i < rvSeedEdit.getChildCount(); i++) {
            CardView cv = (CardView) rvSeedEdit.getChildAt(i);
            EditText et = (EditText) cv.getChildAt(0);

            if (TextUtils.isEmpty(et.getText().toString())) {
                //如果当前为空，就予以赋值
                editSeeds.remove(i);
                editSeeds.add(i, text);
                // adapterEdit.notifyItemChanged(pos);
                adapterEdit.notifyDataSetChanged();
                break;
            }

            //否则就在下一轮进行赋值
        }

        Logger.ds("" + editSeeds.toString());
    }

    /**
     * 种子验证界面上面的item的点击事件
     *
     * @param position 12个item之一
     */
    @Override
    public void onSeedClick(int position, String value) {
        String seed = editSeeds.get(position);

        int count = editSeeds.size();
        //Logger.ds("目前需要验证的助记词有" + count + "个！");

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < count; i++) {
            String element = editSeeds.get(i);
            sb.append(i + ":\t" + element + "\n");
        }

        Logger.ds(seed + "\t当前" + position + "助记词有：\n" + sb.toString() + "\t" + count + "个。");
        //ToastUtils.showToast("传递过来的" + position + ": " + seed);

        //疑点：使用Recycler获得EditText的文本，点击项会为空
        List<String> delLists = new ArrayList<>();

        //将当前点击项乃至最后面的显示文本清空
        for (int i = position; i < editSeeds.size(); i++) {

            String etText = editSeeds.get(i);
            //Logger.ds("当前: " + i + ": " + etText);
            if (TextUtils.isEmpty(etText)) {
                //既然当前项为空，那就没必要执行删除操作了
                //集合当前元素为空，表示后面的也为空，就要跳出循环了
                break;
            }
            Logger.ds("添加" + i + ": " + etText);
            delLists.add(etText);

            //后面使用适配器刷新，故不需
            //et.setText("");
            editSeeds.remove(i);
            editSeeds.add(i, "");
        }

        //Logger.ds("要复原的数量: " + delLists.size());
        StringBuffer sbPres = new StringBuffer();
        for (int i = 0; i < mPreLists.size(); i++) {
            String element = mPreLists.get(i);
            sbPres.append(i + ":\t" + element + "\n");
        }
        //Logger.ds("预览框中的值为: \n" + sbPres.toString());


        //因为下面的是乱序，所以index不能以上面有序的为准
        //把上面列表删掉的item对应下面列表的item状态都复原
        for (int i = 0; i < delLists.size(); i++) {

            for (int j = 0; j < rvSeedWord.getChildCount(); j++) {
                CardView cv = (CardView) rvSeedWord.getChildAt(j);
                TextView tv = (TextView) cv.getChildAt(0);
                //Logger.ds("当前" + j + ":\t" + et.getText().toString());
                String preText = tv.getText().toString();

                if (delLists.get(i).equals(preText)) {
                    Logger.ds("还原item " + j + " 对应的值: " + preText);

                    //还原点击过的项目颜色
                    tv.setEnabled(true);
                }
            }
        }

        //数据源没变，就不用刷新
        //adapterPreview.notifyDataSetChanged();
        //最后将2个列表都刷新下
        adapterEdit.notifyDataSetChanged();
    }

}
